package com.itheima.Controller;

import com.itheima.DTO.ClazzDTO;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/clazzs")
public class ClazzController {

    @Autowired
    private ClazzService clazzService;

    //    该接口用于班级列表数据的条件分页查询
    @GetMapping
    public Result list(ClazzQueryParam clazzQueryParam) {

        log.info("查询请求参数： {}", clazzQueryParam);

        PageResult pageResult = clazzService.pageQuery(clazzQueryParam);
        return Result.success(pageResult);

    }

    //    该接口用于删除班级信息
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) throws Exception {
        log.info("删除班级信息，id：{}", id);

        clazzService.deleteById(id);
        return Result.success();
    }

    //该接口用于添加班级信息
    @PostMapping
    public Result add(@RequestBody Clazz clazz) {
        log.info("新增班级信息：{}", clazz);
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.save(clazz);
        return Result.success();
    }

    //该接口用于根据主键ID查询班级的信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询班级数据：{}", id);

        ClazzDTO clazz = clazzService.getInfo(id);
        return Result.success(clazz);
    }

    //该接口用于修改班级的数据信息
    @PutMapping
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级数据：{}", clazz);
//        clazz.setUpdateTime(LocalDateTime.now());
        clazzService.lambdaUpdate().eq(Clazz::getId, clazz.getId())
                .set(clazz.getName() != null, Clazz::getName, clazz.getName())
                .set(clazz.getRoom() != null, Clazz::getRoom, clazz.getRoom())
                .set(clazz.getBeginDate() != null, Clazz::getBeginDate, clazz.getBeginDate())
                .set(clazz.getEndDate() != null, Clazz::getEndDate, clazz.getEndDate())
//                .set(Clazz::getUpdateTime, clazz.getUpdateTime()) // 添加 updateTime 字段的更新
                .set(Clazz::getUpdateTime,LocalDateTime.now())
                .update();
        return Result.success();
    }

    //该接口用于查询所有班级信息
    @GetMapping("/list")
    public Result list() {
        log.info("查询所有班级信息");

        List<ClazzDTO>  clazzList = clazzService.listAll();
        return Result.success(clazzList);
    }

}
